package griffin.website;

import griffin.logic.UserLogic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.content.pm.ActivityInfo;

public class Bookmark extends Activity {
	private static final String TAG = "[bookmark]";
	private static final String SOAP_ACTION_GETBOOKMARKS = "http://tempuri.org/getBookmarks";
	private static final String SOAP_ACTION_DELETEBOOKMARKS = "http://tempuri.org/deleteBookmarks";
	private static final String METHOD_NAME_GETBOOKMARKS = "getBookmarks";
	private static final String METHOD_NAME_DELETEBOOKMARKS = "deleteBookmarks";
	private static final String NAMESPACE = "http://tempuri.org/";
	// private static final String URL = "http://griffin.ciandt.cn/Sservice1.asmx";
	private static final String URL = "http://192.168.3.130:8080/Sservice1.asmx";
	private List<Map<String, Object>> bookmarkList = new ArrayList<Map<String, Object>>();
	private ListView listView = null;
	private int loginUserID = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "[onCreate...1] ");
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.bookmark);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setNotifyBookmarkUpdatedFlag();
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "[onResume...] ");

		Init();
	}

	private void Init() {
		getLoginInfo();
		getBookmarkList();
	}

	private void getLoginInfo() {
		AtomicReference<String> strUsername = new AtomicReference<String>("");
		AtomicReference<String> strPassword = new AtomicReference<String>("");
		AtomicInteger userid = new AtomicInteger(0);
		UserLogic userLogic = new UserLogic(this);

		if (userLogic.getLoginUser(strUsername, strPassword, userid)) {
			loginUserID = userid.get();
		}
	}

	private void getBookmarkList() {
		if (isLogined()) {
			if (isBookmarkUpdated()) {
				bookmarkList.clear();
				listView = (ListView) this.findViewById(R.id.bookmarklist);
				listView.setAdapter(new BookMarkListAdapter());

				Log.d(TAG, "setAdapter");
			}
		} else {
			askLoginTip();
		}
	}
	
	private boolean isLogined()
	{
		if (loginUserID == 0)
		{
			return false;
		} 
		else 
		{
			return true;
		}
	}

	private boolean isBookmarkUpdated() {
		boolean isUpdated = false;

		SharedPreferences bookmarkUpdateInfo = getSharedPreferences(
				"griffin.website.bookmarkupdatedflag", 0);
		isUpdated = bookmarkUpdateInfo.getBoolean(
				"bookmarkupdatedflagatbookmark", false);
		// reset current activity update flag to false, so current activity will
		// not update again when bookmark not updated.
		setBookmarkUpdatedFlag(false);

		return isUpdated;
	}

	private void setBookmarkUpdatedFlag(boolean flag) {
		SharedPreferences bookmarkupdateInfo = getSharedPreferences(
				"griffin.website.bookmarkupdatedflag", 0);
		SharedPreferences.Editor editor = bookmarkupdateInfo.edit();
		if (bookmarkupdateInfo.contains("bookmarkupdatedflagatbookmark"))
			editor.remove("bookmarkupdatedflagatbookmark");
		editor.putBoolean("bookmarkupdatedflagatbookmark", flag);
		editor.commit();
	}
	
	private void askLoginTip() {
		AlertDialog.Builder builder= new AlertDialog.Builder(Bookmark.this);
		builder.setTitle("You are not sign in.Login now?").setPositiveButton("Yes!",new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface arg0, int arg1) {
				openIntenInView("Login",Bookmark.this);
			}
		});
		builder.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
			public void onClick(DialogInterface dialog, int id) { 
				dialog.cancel(); 									
			} 
		});
		builder.create();
		builder.show();
	}

	public void openIntenInView(String name, Context context) {
		Intent intent = new Intent();
		intent.putExtra("winname", name);
		intent.setClass(context, TabBarFramework.class);
		startActivity(intent);
	}

	class BookMarkListAdapter extends SimpleAdapter {
		public BookMarkListAdapter() {
			super(Bookmark.this,getBookmarkData(loginUserID),R.layout.bookmarklistview,
					new String[]{"Bookmarkname"},
					new int[]{R.id.bookmarkname});
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			HashMap<String, Object> item = (HashMap<String, Object>) bookmarkList
					.get(position);

			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.bookmarklistview, parent,
					false);
			TextView label = (TextView) row.findViewById(R.id.bookmarkname);

			label.setText((String) item.get("Bookmarkname"));
			label.setTag((String) item.get("Bookmarkurl"));
			label.setOnClickListener(new BookmarkClickListener());

			ImageButton reducebookmark = (ImageButton) row
					.findViewById(R.id.minusbookmark);
			reducebookmark.setTag((String) item.get("Bookmarkname"));
			reducebookmark.setOnClickListener(new ReduceButtonListener());

			Log.d(TAG, "[getView ].position(" + position + ")");

			return row;

		}

	}

	private List<Map<String, Object>> getBookmarkData(int userid) {
		if (userid != 0) {
			try {
				SoapObject request = new SoapObject(NAMESPACE,
						METHOD_NAME_GETBOOKMARKS);
				request.addProperty("userid", userid);

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport.call(SOAP_ACTION_GETBOOKMARKS, envelope);

				Object result = (Object) envelope.getResponse();
				try {
					JSONObject jsonObj = new JSONObject(result.toString());
					JSONArray bookmarkArray = jsonObj.getJSONArray("bookmarks");

					for (int i = 0; i < bookmarkArray.length(); i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("Bookmarkurl", bookmarkArray.getJSONObject(i)
								.getString("Bookmarkurl"));
						map.put("Bookmarkname", bookmarkArray.getJSONObject(i)
								.getString("Bookmarkname"));
						bookmarkList.add(map);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return bookmarkList;
	}

	class ReduceButtonListener implements View.OnClickListener {
		public void onClick(View v) {
			ImageButton reducebookmark = (ImageButton) v;
			String bookmarkname = reducebookmark.getTag().toString().trim();

			deleteBookmark(loginUserID, bookmarkname);
			refreshBookmarkList();
		}
	}

	class BookmarkClickListener implements View.OnClickListener {
		public void onClick(View v) {
			TextView clickbookmark = (TextView) v;
			String bookmarkurl = clickbookmark.getTag().toString().trim();
			openUrl(bookmarkurl);
		}
	}

	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	private void deleteBookmark(int userid, String bookmarkname) {
		if (isLogined()) {
			try {
				SoapObject request = new SoapObject(NAMESPACE,
						METHOD_NAME_DELETEBOOKMARKS);
				request.addProperty("userid", userid);
				request.addProperty("bookmarkName", bookmarkname);

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport
						.call(SOAP_ACTION_DELETEBOOKMARKS, envelope);

				setNotifyBookmarkUpdatedFlag();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void setNotifyBookmarkUpdatedFlag() {
		SharedPreferences bookmarkupdateInfo = getSharedPreferences(
				"griffin.website.bookmarkupdatedflag", 0);
		SharedPreferences.Editor editor = bookmarkupdateInfo.edit();
		if (bookmarkupdateInfo.contains("bookmarkupdatedflagathome"))
			editor.remove("bookmarkupdatedflagathome");
		if (bookmarkupdateInfo.contains("bookmarkupdatedflagatbookmark"))
			editor.remove("bookmarkupdatedflagatbookmark");
		// notify home activity to update bookmark list
		editor.putBoolean("bookmarkupdatedflagathome", true);
		// notify bookmark activity to update bookmark list
		editor.putBoolean("bookmarkupdatedflagatbookmark", true);
		editor.commit();
	}

	private void refreshBookmarkList() {
		getBookmarkList();
	}

}